import base64
import json
from datetime import datetime
import logging
from django.http import JsonResponse
from lapi_app.models.user_model.user_info import Userinfo
from django.views import View

logger = logging.getLogger('django')


class User_login(View):
    def post(self, request, *args, **kwargs):
        """
        用户据登录接口
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        try:
            data = json.loads(request.body)
            u = data["account"]
            p = data["password"]
            users = Userinfo.objects.filter(account=u, password=p)
            if users:
                for user in users:
                    token = users.update(token=base64.b64encode(str.encode(json.dumps(data))).decode('utf-8'), token_time=datetime.now())
                    return JsonResponse(
                        {
                            "code": 200,
                            "message": "登录成功",
                            "login_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                            "user_id": user.id,
                            "username": u,
                            # "token": str(token.token.decode('utf-8'))
                        })
            else:
                return JsonResponse({
                    "code": 100,
                    "message": "账号或密码错误",
                    "login_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                })
        except Exception as e:
            return JsonResponse({
                "code": 100,
                "message": "登录失败，原因：" + str(e)
            })
